package com.lujieni.springbooticbc.service.impl;

import com.alibaba.fastjson.JSON;
import com.lujieni.springbooticbc.dao.ScanServiceConfigDao;
import com.lujieni.springbooticbc.dao.StudentDao;
import com.lujieni.springbooticbc.entity.ScanServiceConfigPO;
import com.lujieni.springbooticbc.entity.SreLog;
import com.lujieni.springbooticbc.service.IAlarmTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Optional;

@Service
public class ScanService implements ApplicationRunner {

    @Autowired
    private ScanServiceConfigDao scanServiceConfigDao;
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Autowired
    private ApplicationContext applicationContext;

    private final Logger sreLog = LoggerFactory.getLogger("sreLog");
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Callback used to run the bean.
     *
     * @param args incoming application arguments
     * @throws Exception on error
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Optional.ofNullable(scanServiceConfigDao.selectAll()).ifPresent(item ->{
            for (ScanServiceConfigPO po : item) {
                threadPoolTaskScheduler.schedule(()->{
                    execute(po);
                }, new CronTrigger(po.getCron()));
            }
        });
    }

    private void execute(ScanServiceConfigPO po) {
        try{
            if(!StringUtils.isEmpty(po.getSyncWriteBeanClass())){
                Example example = new Example(Class.forName(po.getSyncWriteEntityClass()));
                Mapper mapper = (Mapper) applicationContext.getBean(Class.forName(po.getSyncWriteBeanClass()));
                example.createCriteria().andEqualTo(po.getColumnCondition(), "女");
                List<?> list = mapper.selectByExample(example);
                logger.info(JSON.toJSONString(list));
            }
        }catch (Exception e){
            logger.error("scan service config error", e);
        }
    }

}
